﻿using System;
using System.Buffers;
using SuperSocket.ProtoBase;

namespace FixedHeaderSample.SocketServer.Server
{
    public class MyPipelineFilter : FixedHeaderPipelineFilter<MyPackageInfo>
    {
        /// +-------+---+----------------------+
        /// |request| l |                      |
        /// | type  | e |     request body     |
        /// |  (2)  | n |                      |
        /// |       |(2)|                      |
        /// +-------+---+----------------------+

        private const int HeaderSize = 4; //Header总长度
        private const int HeaderLenOffset = 2; //长度offset

        public MyPipelineFilter()
            : base(HeaderSize) //包头大小是4字节，所以将4传入基类构造方法
        {

        }

        //从数据包的头部返回包体的大小
        protected override int GetBodyLengthFromHeader(ref ReadOnlySequence<byte> buffer)
        {
            var reader = new SequenceReader<byte>(buffer);
            reader.Advance(HeaderLenOffset); //跳过前2个字节
            reader.TryReadBigEndian(out short len); //以大端方式读取short类型数据
            reader.Rewind(4);
            reader.TryRead(out var byte1);
            reader.TryRead(out var byte2);
            reader.TryRead(out var byte3);
            reader.TryRead(out var byte4);
            Console.WriteLine($@"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} len = {len}, " +
                              $@"{byte1:X2}, {byte2:X2}, {byte3:X2}, {byte4:X2}");
            return len - HeaderSize;
        }

        protected override MyPackageInfo DecodePackage(ref ReadOnlySequence<byte> buffer)
        {
            var reader = new SequenceReader<byte>(buffer);
            reader.TryReadBigEndian(out short packageKey);

            var body = buffer.Slice(HeaderSize).ToArray();
            return new MyPackageInfo
            {
                Key = packageKey,
                Body = body
            };
        }
    }
}
